#!/usr/bin/env python
# -*- coding: utf8 -*-
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      iori
#
# Created:     21-02-2014
# Copyright:   (c) iori 2014
# Licence:     <your licence>
#-------------------------------------------------------------------------------

from Tkinter import *
import Image, ImageTk
import os
from StringIO import StringIO


class Verify(Frame):
    def __init__(self, master, ds, fn=''):
        Frame.__init__(self, master )
        self.btn = Button(self, command=self.def_cmd)
        self.btn.pack(side=TOP)
        self.photo = None
        self.ds = ds
        if ds:
            self.def_cmd()
        self.code = StringVar()
        ent = Entry(self, textvariable=self.code)
        ent.pack(side=BOTTOM)
        ent.bind('<Return>', fn if fn else self.enter_key)
        self.pack()

    def def_cmd(self):
        if not self.ds: return
        try:
            source = self.ds.next()
        except StopIteration:
            self.ds = None
            return
        else:
            self.update_image(source)

    def update_image(self, source=''):
        if not source:
            return
        if not os.path.isfile(source):
            source = StringIO(source)
        img = Image.open(source)
        width, height = img.size
        self.photo = ImageTk.PhotoImage(img)
        # photo不能是临时变量
        self.btn.config(image=self.photo, width=width,height=height)

    def enter_key(self, event):
        print self.code.get()


class VerifyFrame(Frame):
    def __init__(self, master, fn=''):
        Frame.__init__(self, master )
        self.vimg = Label(self)
        self.vimg.pack(side=TOP)
        self.photo = None
        self.code = StringVar()
        ent = Entry(self, textvariable=self.code)
        ent.pack(side=BOTTOM)
        ent.bind('<Return>', fn if fn else self.enter_key)
        self.pack()

    def update_image(self, source=''):
        if not source:
            return
        if len(source) >1024  or (not os.path.isfile(source)):
            source = StringIO(source)
        img = Image.open(source)
        width, height = img.size
        self.photo = ImageTk.PhotoImage(img)
        # photo不能是临时变量
        self.vimg.config(image=self.photo, width=width,height=height)

    def enter_key(self, event):
        print self.code.get()



def test_fun(vc):
    vc.update_image(vc.code.get())

def main():
    root = Tk()
    ds = ('{}.jpg'.format(_) for _ in range(2, 5))
    vc = Verify(root, ds=ds, fn=test_fun)
    root.mainloop()
    pass

if __name__ == '__main__':
    main()

